<template>
	<view class="cost-container">
		<view class="modle-info-box" v-for="(item,index) in detailsList" :key="index">
			<view class="info-top flexWrap">
				<text>成本明细{{detailsList.length>1 ? index+1 : ''}}</text>
				<text class="del" v-if="detailsList.length>1" @tap="handleDelete(index)">删除</text>
			</view>
			<view class="info-list">
				<view class="info-item flexWrapNo" style="flex: 1;">
					<view>费用类型：</view>
					<picker @change="bindTypeChange" :data-index="index" :value="typeIndex" :range="typeArray" range-key="label">
						<view class="select-input" v-if="item.type">{{formatType(item.type)}}</view>
						<view class="select-input" v-else>请选择</view>
					</picker>
					<text class="icon-more"></text>
				</view>
				<view class="info-item flexWrap">
					<view class="flexWrapNo" style="flex: 1;">
						<view>发生时间：</view>
						<picker mode="date" :data-index="index" :value="item.costDate" @change="bindDateChange" :start="firstDay" :end="lastDay">
							<view class="select-input" v-if="item.costDate">{{item.costDate}}</view>
							<view class="select-input" v-else>请选择</view>
						</picker>
					</view>
					<text class="icon-more"></text>
				</view>
				
				<view class="info-item flexWrap">
					<view class="flexWrapNo" style="flex: 1;">
						<view>费用金额：</view>
						<input placeholder="请填写" 
							placeholder-class="placeholderclass" 
							v-model="item.amount" type="digit"
						/>
					</view>
				</view>
				<view class="info-item flexWrap">
					<view class="flexWrapNo" style="flex: 1;align-items: flex-start;">
						<view style="flex-shrink: 0;">费用说明：</view>
						<textarea v-model="item.desc"
							placeholder-class="placeholderclass" 
							placeholder="请填写" 
						/>
					</view>
				</view>
				
				<view class="info-item">
					<view>附件：</view>
					<view class="attachment-box flexWrapNo">
						<view @tap="previewImage(val,item.imageList)" class="attachment-img"
							v-for="(val,k) in item.imageList" :key="k">
							<image :src="val" mode="aspectFill"></image>
							<image src="@/static/user/close.png" class="close-btn"
								@tap.stop="deleteImage(index,k)"></image>
						</view>
						<view class="add-btn" @tap="chooseImage(index)" v-if="item.imageList.length<3"></view>
					</view>
					<view class="attachment-tips">请上传后成本凭证，最多上传3张图片，仅支持jpg、jpeg、png格式图片</view>
				</view>
			</view>
		</view>
		
		<view class="add-btn flexWrapNo" @tap="handleAdd" v-if="!id">
			<uni-icons type="plus" size="20" color="#26BCFD"></uni-icons>
			增加明细
		</view>
		
		<view class="bottom-btn" @tap="submit">提交保存</view>
	</view>
</template>

<script>
	import base from '@/common/base.js';
	import utils from '@/common/lib/util.js'
	export default{
		data(){
			return{
				id:null,
				firstDay:'',
				lastDay:'',
				imageLength:3,
				detailsList:[
					{
						type:'',
						costDate:'',
						amount:'',
						desc:'',
						attachment:'',
						imageList:[],
						uploadList:[],
					}
				],
				typeArray:[
					{label:'电费',value:1},
					{label:'水费',value:2},
					{label:'保洁费',value:3},
					{label:'维护费',value:4},
					{label:'房租',value:5},
					{label:'自采',value:6},
					{label:'商城采购',value:7},
					{label:'其他',value:9},
				],
				typeIndex:'',
				detailsIndex:'',
			}
		},
		onLoad(options){
			this.id=options.id
			if(this.id){
				this.getDetails()
			}
			this.getFirstAndLastDayOfMonth()
		},
		methods:{
			// 获取当月的第一天和最后一天
			getFirstAndLastDayOfMonth(){
				const today = new Date()
				const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
				const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
				this.firstDay=this.formatDate(firstDayOfMonth)
				this.lastDay=this.formatDate(lastDayOfMonth)
			},
			
			// 时间格式转化为字符串格式
			formatDate(date){
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`
			},
			
			// 获取详情
			getDetails(){
				this.$request.get(this.$api.getCostDetail, {
					id:this.id
				}, {
					isJava: true
				}).then(res => {
					if(res.code==200){
						let {
							data = {}
						} = res;
						this.detailsList=[]
						let temp=data
						temp.imageList=temp.attachment.split(',')
						temp.uploadList=temp.attachment.split(',')
						this.detailsList.push(temp)
					}
				})
			},
			
			bindTypeChange(e){
				let index = e.currentTarget.dataset.index
				this.typeIndex = e.detail.value
				this.detailsList[index].type=this.typeArray[this.typeIndex].value
			},
			
			bindDateChange(e){
				let index = e.currentTarget.dataset.index
				this.detailsList[index].costDate = e.target.value
			},
			
			// 回显费用类型
			formatType(value){
				let foundData = this.typeArray.find(item => item.value ==value)
				return foundData.label
			},
			
			//删除图片
			deleteImage(index,k) {
				// this.imageList.splice(index, 1)
				// this.uploadList.splice(index, 1)
				this.detailsList[index].imageList.splice(k,1)
				this.detailsList[index].uploadList.splice(k,1)
			},
			
			chooseImage: async function(index) {
				var that = this
				that.detailsIndex=index
				uni.chooseImage({
					// count: this.imageLength - this.imageList.length,
					count: this.imageLength - this.detailsList[this.detailsIndex].imageList.length,
					extension: ['.jpg', '.png', '.jpeg'],
					success: (res) => {
						console.log(res)
						for (let i in res.tempFilePaths) {
							var imgFiles = res.tempFilePaths[i]
							let suffix = res.tempFilePaths[i].split('.')[1]
							// console.log(suffix)
							if (suffix != 'jpg' && suffix != 'png' && suffix != 'jpeg') {
								this.$tools.showToast('图片仅支持jpg、jpeg、png');
								return;
							}
							that.cutImageCallback(imgFiles);
						}
						// that.imageList = that.imageList.concat(res.tempFilePaths)
						that.detailsList[that.detailsIndex].imageList=that.detailsList[that.detailsIndex].imageList.concat(res.tempFilePaths)
					}
				})
			},
			
			cutImageCallback(content) {
				let that = this;
				let httpsHead = 'https://moyu24h-new.oss-cn-chengdu.aliyuncs.com/'
				that.$tools.loadIng('上传中,请稍后..')
				base.aliyun_upload(content, function(r, err) {
					if (r) {
						let uploadimg = httpsHead + r
						// console.log(r)
						// that.uploadList = that.uploadList.concat(uploadimg);
						that.detailsList[that.detailsIndex].uploadList=that.detailsList[that.detailsIndex].uploadList.concat(uploadimg)
						uni.hideLoading();
					}
				})
			},
			
			handleAdd(){
				this.typeIndex=''
				this.detailsList.push({
					type:'',
					costDate:'',
					amount:'',
					desc:'',
					attachment:'',
					imageList:[],
					uploadList:[],
				})
			},
			
			handleDelete(i){
				this.detailsList.splice(i,1)
			},
			
			submit:utils.debounce(function(){
				let arr=[]
				this.detailsList.forEach(item=>{
					arr.push({
						storeId:uni.getStorageSync('store_id'),
						id:this.id,
						costDate:item.costDate,
						type:item.type,
						amount:item.amount,
						desc:item.desc,
						attachment:item.uploadList.join(','),
					})
				})
				
				for(let i=0;i<arr.length;i++){
					if(!arr[i].type){
						this.$tools.showToast('费用类型不能为空')
						return
					}else if(!arr[i].costDate){
						this.$tools.showToast('发生时间不能为空')
						return
					}else if(!arr[i].amount){
						this.$tools.showToast('费用金额不能为空')
						return
					}else if(!arr[i].desc){
						this.$tools.showToast('费用描述不能为空')
						return
					}else if(!arr[i].attachment){
						this.$tools.showToast('附件不能为空')
						return
					}
				}
				
				if(this.id){
					this.$request.post(this.$api.editCostDetail, arr, {
						isJava: true
					}).then(res => {
						if(res.code==200){
							let {
								data = {}
							} = res;
							this.$tools.showToast('修改成功')
							setTimeout(()=>{
								uni.navigateBack()
							},700)
						}
					})
				}else{
					this.$request.post(this.$api.addCostDetail, arr, {
						isJava: true
					}).then(res => {
						if(res.code==200){
							let {
								data = {}
							} = res;
							this.$tools.showToast('添加成功')
							setTimeout(()=>{
								uni.navigateBack()
							},700)
						}
					})
				}
			},1000),
		},
	}
</script>

<style lang="scss" scoped>
	.cost-container{
		padding: 28rpx;
		padding-bottom: 50rpx;
	}
	/deep/.modle-info-box {
		border: 1rpx solid rgba(255, 255, 255, 0.2);
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		.info-top{
			background: #1D1C5C;
			color: #fff;
			padding: 10rpx 20rpx;
			font-size: 28rpx;
			.del{
				color:#26BCFD;
			}
		}
		.info-list{
			padding: 0 20rpx;
		}
		.info-item {
			font-size: 28upx;
			font-family: PingFang SC;
			font-weight: 400;
			line-height: 40upx;
			color: #FFFFFF;
			padding: 30upx 0;
			border-bottom: 1upx solid #36355E;
			position: relative;
			&:last-child{
				border: none;
			}
			picker{
				flex: 1;
			}
			.select-input{
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #FFE577;
				flex: 1;
			}
			input {
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #FFE577;
				flex: 1;
			}
			textarea{
				border: 2rpx solid #36355E;
				border-radius: 8rpx;
				padding: 10rpx 20rpx;
				width: 100%;
				height: 150rpx;
				box-sizing: border-box;
				color: #FFE577;
			}
			.icon-more {
				border-color: #FFFFFF;
				position: absolute;
				right: 20rpx;
				pointer-events: none;
			}
	
			.placeholderclass {
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #FFE577;
			}
		}	
	}
	
	.attachment-box {
		margin-top: 30upx;
		flex-wrap: wrap;
		gap: 20rpx;
		.add-btn {
			width: 156rpx;
			height: 156rpx;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			border: 1upx solid #36355E;
			position: relative;
			flex-shrink: 0;
	
			&::after {
				content: "";
				display: inline-block;
				width: 40upx;
				height: 4upx;
				background: #36355E;
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				margin: auto;
			}
	
			&::before {
				content: "";
				display: inline-block;
				width: 4upx;
				height: 40upx;
				background: #36355E;
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				margin: auto;
			}
		}
	
		.attachment-img {
			width: 156rpx;
			height: 156rpx;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			position: relative;
			flex-shrink: 0;		
			.close-btn {
				position: absolute;
				top: -10upx;
				right: -10upx;
				width: 40upx;
				height: 40upx;
			}
		}
	}
	
	.attachment-tips {
		font-size: 24upx;
		margin-top: 20upx;
	}
	
	.add-btn{
		color: #26BCFD;
		font-size: 28rpx;
	}
	
	.bottom-btn{
		width: 670rpx;
		height: 80rpx;
		margin: 30rpx auto;
		background: rgb(31, 124, 247);
		border-radius: 72rpx;
		font-size: 34rpx;
		color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>